package org.cid54.jshopper.dao.impl;

import java.util.List;
import org.cid54.jshopper.dao.SuperEntityDao;
import org.cid54.jshopper.model.SuperEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @param <T> 
 * @author fgo
 */
public abstract class SuperEntityDaoImpl<T extends SuperEntity> implements SuperEntityDao<T> {

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }

    protected Criteria getNewCriteria() {
        return this.getSession().createCriteria(this.getEntityClass());
    }

    protected abstract Class getEntityClass();

    protected abstract boolean isSortableByName();

    @Override
    public void create(T t) {
        this.getSession().persist(t);
    }

    @Override
    public void update(T t) {
        this.getSession().update(t);
    }

    @Override
    public void delete(T t) {
        this.getSession().delete(t);
    }

    @Override
    public T findById(long id) {
        return (T) this.getSession().load(this.getEntityClass(), id);
    }

    @Override
    public List<T> getAll() {

        Criteria criteria = this.getNewCriteria();

        if (this.isSortableByName()) {
            criteria.addOrder(Order.asc("name"));
        }

        return criteria.list();
    }
}
